<?php
App::uses('AppController', 'Controller');
App::import('Vendor', 'Uploader.Uploader');
/**
 * Products Controller
 *
 * @property Product $Product
 */
class ProductsController extends AppController {

    public $uses = array('Image', 'Product', 'ImageProduct', 'Category');

    public function beforeFilter() {
        $this->Uploader = new Uploader(array(
            'ajaxField' => 'qqfile'
        ));

    }

/**
 * index method
 *
 * @return void
 */
    public function index() {
        $this->Product->recursive = 0;
        $this->set('products', $this->paginate());
    }

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
    public function view($id = null) {
        if (!$this->Product->exists($id)) {
            throw new NotFoundException(__('Invalid product'));
        }
        $options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
        $this->set('product', $this->Product->find('first', $options));
    }

/**
 * add method
 *
 * @return void
 */
    public function add() {
        if ($this->request->is('post')) {
            $this->Product->create();
            if ($this->Product->save($this->request->data)) {
                $this->Session->setFlash(__('The product has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The product could not be saved. Please, try again.'));
            }
        }
        $providers = $this->Product->Provider->find('list');
        $categories = $this->Product->Category->find('list');
        $lev2 = $this->Product->Category->find('list', array('fields' => array('Category.id', 'Category.title'), 'conditions' => array('Category.lev' => 2)));
        $lev3 = $this->Product->Category->find('list', array('fields' => array('Category.id', 'Category.title'), 'conditions' => array('Category.lev' => 3)));
        $this->set(compact('providers', 'categories', 'lev2', 'lev3'));
    }

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
    public function edit($id = null) {
        if (!$this->Product->exists($id)) {
            throw new NotFoundException(__('Invalid product'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Product->save($this->request->data)) {
                $this->Session->setFlash(__('The product has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The product could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
            $this->request->data = $this->Product->find('first', $options);
        }
        $providers = $this->Product->Provider->find('list');
        $categories = $this->Product->Category->find('list');
        $this->set(compact('providers', 'categories'));
    }

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
    public function delete($id = null) {
        $this->Product->id = $id;
        if (!$this->Product->exists()) {
            throw new NotFoundException(__('Invalid product'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Product->delete()) {
            $this->Session->setFlash(__('Product deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Product was not deleted'));
        $this->redirect(array('action' => 'index'));
    }

/**
 * admin_index method
 *
 * @return void
 */
    public function admin_index() {

        // $title_for_layout = 'Product';
        // $this->set(compact('title_for_layout'));
        $this->ImageProduct->recursive = 0;
        $this->paginate = array(
        'Product' => array(
            'limit' => 16,
            //'conditions' => array('Category.category_type' => 2),
            // 'order' => array('SetOfMovie.sm_id' => 'DESC'),
            //'group' => array('week', 'home_team_id', 'away_team_id')
        )
        );
        $products = $this->paginate('Product');
        $this->set(compact('products'));
    }

/**
 * admin_view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
    public function admin_view($id = null) {
        if (!$this->Product->exists($id)) {
            throw new NotFoundException(__('Invalid product'));
        }
        $options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
        $this->set('product', $this->Product->find('first', $options));
    }

/**
 * admin_add method
 *
 * @return void
 */
    public function admin_add() {
        $this->Uploader->uploadDir = '/img/products/';
        if ($this->request->is('ajax')) {
            $datai['name'] = $_FILES['images']['name'][0];
            $datai['type'] = $_FILES['images']['type'][0];
            $datai['tmp_name'] = $_FILES['images']['tmp_name'][0];
            $datai['error'] = $_FILES['images']['error'][0];
            $datai['size'] = $_FILES['images']['size'][0];
            // debug($datai);die;
              if ($data = $this->Uploader->upload($datai, array('name' => 'uploaderFilename', 'overwrite' => false))) {
                $path = $this->Uploader->resize(array('width' => 308, 'height' => 320, 'expand' => true, 'aspect' => false));
                $dataimg['name'] = $data['custom_name'].'-resized-' . '308' . 'x' . '320';
                $dataimg['link'] = $path;
                $this->Uploader->delete($data['path']);
                $this->Image->create();
                if ($this->Image->save($dataimg)) {
                  $last_id_img = $this->Image->getInsertId();
                  $this->Session->write('username.lastidimg', $last_id_img);
                } else {
                    $this->Session->setFlash(__('The image could not be saved. Please, try again.'));
                }
            }
             exit;
        }

        if ($this->request->is('post')) {
            $last_id_img = $this->Session->read('username.lastidimg');
            $this->Product->create();
            $this->ImageProduct->create();
            if ($this->Product->save($this->request->data)) {
                 $data_IP['product_id'] = $this->Product->getInsertId();
                 $data_IP['image_id'] = $last_id_img;
                $this->ImageProduct->save($data_IP);
                 debug($data_IP);
                $this->Session->setFlash(__('The product has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The product could not be saved. Please, try again.'));
            }

        }
        $providers = $this->Product->Provider->find('list');
        $categories = $this->Product->Category->find('list');
        $lev1 = $this->Product->Category->find('list', array('fields' => array('Category.id', 'Category.title'), 'conditions' => array('Category.lev' => 1)));
        $lev2 = $this->Product->Category->find('all', array('fields' => array('Category.id', 'Category.title', 'Category.sub'), 'conditions' => array('Category.lev' => 2)));
        $sub2 = $this->Category->find('list', array('fields' => array('Category.sub'), 'conditions' => array('Category.lev' => 2)));
        $sub3 = $this->Category->find('list', array('fields' => array('Category.sub'), 'conditions' => array('Category.lev' => 3)));
        $lev3 = $this->Product->Category->find('all', array('fields' => array('Category.id', 'Category.title', 'Category.sub'), 'conditions' => array('Category.lev' => 3)));
        $this->set(compact('providers', 'categories', 'lev2', 'lev3', 'lev1', 'sub2', 'sub3'));
    }

/**
 * admin_edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
    public function admin_edit($id = null) {
        if (!$this->Product->exists($id)) {
            throw new NotFoundException(__('Invalid product'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Product->save($this->request->data)) {
                $this->Session->setFlash(__('The product has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The product could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id));
            $this->request->data = $this->Product->find('first', $options);
        }
        $images = $this->ImageProduct->findAllByProductId($id, array('fields'=>'Image.link'));
        // debug($images);
        $providers = $this->Product->Provider->find('list');
        $categories = $this->Product->Category->find('list');
        $this->set(compact('providers', 'categories'));
    }

/**
 * admin_delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
    public function admin_delete($id = null) {
        $this->Product->id = $id;
        $dataold = $this->ImageProduct->findAllByProductId($id);
        $imgid = $dataold[0]['Image']['id'];
        $imgpath = $dataold[0]['Image']['link'];
        //debug($imgid);die;
        if (!$this->Product->exists()) {
            throw new NotFoundException(__('Invalid product'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Product->delete()) {

            $this->Image->id = $imgid;
             if ($this->Image->delete()) {
            $this->Uploader->delete($imgpath);
             }
            $this->ImageProduct->deleteAll(array('ImageProduct.product_id' => $id), false);
            $this->Session->setFlash(__('Product deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Product was not deleted'));
        $this->redirect(array('action' => 'index'));
    }
}
